package andev.schoolhelper.main;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

import andev.aandroidlib.activity.ANetActivity;
import andev.aandroidlib.listener.ATouch;
import andev.schoolhelper.R;
import andev.schoolhelper.login.LoginActivity;

public class MainActivity extends ANetActivity {
    /* Angus
     * 2015年7月14日 下午4:57:54
     * 设置Tab监听
     */
    private static int CheckedRadio = 0;
    /* Angus
     * 2015年7月17日 下午6:08:06
     * Actionbar
     */
    public RelativeLayout actionbarLayout;
    public FragmentManager fragmentManager;
    private ImageView actionbar_menu;
    private TextView actionbar_middle_tv;
    /* Angus
     * 2015年7月13日 上午9:31:01
     * SlidingMenu
     */
    private SlidingMenu slidingMenu;
    private GridLayout slidingMenu_options_grid;
    private RadioGroup radioGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        InitActionBar();
        InitSlidingMenu(this);
        setTabListen(null);
    }

    public ImageView getActionbar_menu() {
        return actionbar_menu;
    }

    public TextView getActionbar_middle_tv() {
        if (actionbar_middle_tv == null) {
            actionbar_middle_tv = new TextView(this);
        }
        return actionbar_middle_tv;
    }

    private void InitActionBar() {
        actionbarLayout = (RelativeLayout) setCustomActionBar(R.layout.myactionbar);

        actionbar_menu = (ImageView) findViewById(R.id.actionbar_menu);
    }

    private void InitSlidingMenu(Activity context) {
        slidingMenu = new SlidingMenu(context);
        slidingMenu.setMenu(R.layout.activity_slidingmenu);

        slidingMenu.setMode(SlidingMenu.LEFT);
        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        slidingMenu.attachToActivity(context, SlidingMenu.SLIDING_WINDOW);

		/*设置slidingMenu的尾部偏移，避免全屏*/
        slidingMenu.setBehindOffsetRes(R.dimen.dimen_slidingmenu_offset);

		/*以下为非原版功能*/
        slidingMenu.setAboveCanvasTransformer(new SlidingMenu.CanvasTransformer() {
            @Override
            public void transformCanvas(Canvas canvas, float percentOpen) {
                float scale = (float) (1 - percentOpen * 0.25);
                canvas.scale(scale, scale, 0, canvas.getHeight() / 2);
            }
        });
        slidingMenu.setBackgroundResource(R.mipmap.ic_bkg_slidingmenu);

		/* Angus
		 * 2015年7月13日 上午9:31:01
		 * SlidingMenu提取用户信息
		 */
        SharedPreferences loginPreferences = getApplicationContext().getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
        TextView nicknameTV = (TextView) findViewById(R.id.nicknameTV);
        nicknameTV.setText(loginPreferences.getString("nickname", "获取昵称失败"));

        InitSlidingMenuOptions();
    }

    private void InitSlidingMenuOptions() {
        slidingMenu_options_grid = (GridLayout) findViewById(R.id.slidingMenu_options_grid);
        int childCount = slidingMenu_options_grid.getChildCount();
        for (int i = 0; i < childCount; i++) {
            int width = (int) ((getScreenSize().x - getResources().getDimension(R.dimen.dimen_slidingmenu_offset) - 5 * 3) / 2);
            LinearLayout linearLayout = (LinearLayout) slidingMenu_options_grid.getChildAt(i);

            GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
            layoutParams.width = layoutParams.height = width;
            layoutParams.setMargins(5, 0, 0, 5);

            linearLayout.setLayoutParams(layoutParams);

            final int id = linearLayout.getId();
            linearLayout.setOnTouchListener(new ATouch() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        switch (id) {
                            case R.id.option_logout:
                                SharedPreferences loginPreferences = getApplicationContext().getSharedPreferences("Login", Context.MODE_PRIVATE);
                                SharedPreferences.Editor editor = loginPreferences.edit();
                                editor.putBoolean("bAlreadyLogin", false);
                                editor.commit();

                                goActivity(LoginActivity.class);
                                break;

                            default:
                                break;
                        }
                    }
                    return super.onTouch(v, event);
                }
            });

        }
    }

    /* @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
     * Angus
     * 2015年7月13日
     * 重写意图——点击硬件菜单按钮开关slidingMenu
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                slidingMenu.toggle(true);
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /* @see android.app.Activity#onBackPressed()
     * Angus
     * 2015年7月14日
     * 重写意图——点击后退按钮，判断是关闭抽屉还是关闭Activity
     */
    @Override
    public void onBackPressed() {
        if (slidingMenu.isMenuShowing()) {
            slidingMenu.toggle(true);
            return;
        }
        super.onBackPressed();
    }

    public void setTabListen(RadioGroup.OnCheckedChangeListener tabListener) {
        radioGroup = (RadioGroup) findViewById(R.id.RG_tab);
        fragmentManager = getFragmentManager();
        if (tabListener != null) {
            radioGroup.setOnCheckedChangeListener(tabListener);
            return;
        }

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                Fragment newFragment = null;
                switch (checkedId) {
                    case R.id.tab_msg:
                        newFragment = new MSGFragment();
                        break;
                    case R.id.tab_course:
                        newFragment = new CourseFragment();
                        break;
                    case R.id.tab_explore:
                        newFragment = new ExploreFragment();
                        break;
                }
                if (newFragment != null) {
                    fragmentTransaction.replace(R.id.MainFrameLayout, newFragment);
                    fragmentTransaction.commit();
                }
            }
        });

        if (CheckedRadio == 0) {
            //该方法导致onCheckChanged被触发多次，不适合使用
            //radioGroup.check(R.id.tab_course);

            ((RadioButton) findViewById(R.id.tab_course)).setChecked(true);
            CheckedRadio = R.id.tab_course;
        } else {
            ((RadioButton) findViewById(CheckedRadio)).setChecked(true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        CheckedRadio = radioGroup.getCheckedRadioButtonId();
    }


}
